package com.oscarmovie;

import java.util.List;

import tt.util.IOUtils;

public class Oracle2MySQL {
	private static final String ORIGIN = 		"WEB-INF/db/oracle/InitData.sql";
	private static final String DESTINATION = 	"WEB-INF/db/mysql/InitData.sql";
	private static final String CHARSET = "UTF-8";
	
	public static void main(String[] args) {

		List<String> sqls = IOUtils.readFileAsList(ORIGIN, CHARSET);
		StringBuilder convertedSqls = new StringBuilder();
		long t1 = System.currentTimeMillis();
		for(String sql: sqls){
			sql = removeComment(sql);
			sql = removeTT(sql);
			sql = removeREM(sql);
			sql = removeTODATE(sql);
			sql = lowercase(sql);
			convertedSqls.append(sql).append("\n");
			
		}
		long t2 = System.currentTimeMillis();
		System.out.println("Time: "+(t2-t1));
		
		IOUtils.writeFile(DESTINATION, convertedSqls, CHARSET);
		
	}
	private static String removeComment(String sql){
		if(sql.startsWith("--")){
			sql = "";
		}
		return sql;
	}
	
	private static String removeTT(String sql){
		return sql.replaceAll("TT.", "");
	}
	
	private static String removeREM(String sql){
		if(sql.startsWith("REM INSERTING")){
			sql = "";
		}
		return sql;
	}
	
	private static String removeTODATE(String sql){
		if(sql.indexOf("to_date")!=-1){
			sql = sql.replaceAll("to_date[(]", "");
			sql = sql.replaceAll(",'YYYY-MM-DD HH24:MI:SS'[)]", "");
		}
		return sql;
	}
	
	private static String lowercase(String sql) {
		String pattern = "Insert into ";
		if(sql.indexOf(pattern)!=-1){
			int p1 = sql.indexOf(pattern)+pattern.length();
			int p2 = sql.indexOf("(",p1);
			String table = sql.substring(p1,p2).toLowerCase();
			sql = pattern + table + sql.substring(p2);
		}
		return sql;
	}
}
